﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Text;
using Infov1.Models;
using Infov1.Commands;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System.Collections.ObjectModel;
using Infov1.Models.Communication;
using HandyControl.Controls;
using Infov1.Models.WorkForm;
using Infov1.Models.WorkRecord;
using SqlSugar;
using System.Windows.Input;


namespace Infov1.ViewModels.WorkForm
{
    public class CustomerSummaryViewModel : ViewModelBase
    {
        private readonly SqlSugar.ISqlSugarClient _db;
        //开始日期
        private DateTime _startDate;
        public DateTime StartDate
        {
            get => _startDate;
            set
            {
                _startDate = value;
                OnPropertyChanged(nameof(StartDate));
            }
        }
        //定义结束日期
        private DateTime _endDate;
        public DateTime EndDate
        {
            get => _endDate;
            set
            {
                _endDate = value;
                OnPropertyChanged(nameof(EndDate));
            }
        }
        // 定义操作员列表
        private ObservableCollection<AdminModel> _admins = new ObservableCollection<AdminModel>();
        public ObservableCollection<AdminModel> Admins
        {
            get => _admins;
            set => SetProperty(ref _admins, value);
        }
        //定义选中的操作员
        private AdminModel _selectedOperator;
        public AdminModel SelectedOperator
        {
            get => _selectedOperator;
            set
            {
                SetProperty(ref _selectedOperator, value);

            }
        }
        //定义客户列表
        private ObservableCollection<CustomerInfoModel> _customers = new ObservableCollection<CustomerInfoModel>();
        public ObservableCollection<CustomerInfoModel> Customers
        {
            get => _customers;
            set
            {
                _customers = value;
                OnPropertyChanged(nameof(Customers));
            }
        }
        //定义选中的客户
        private CustomerInfoModel _selectedCustomer;
        public CustomerInfoModel SelectedCustomer
        {
            get => _selectedCustomer;
            set
            {
                SetProperty(ref _selectedCustomer, value);
                /*if (value != null)
                {
                    var message = new System.Text.StringBuilder();
                    message.AppendLine($"客户名称：{value.CompanyName}");
                    message.AppendLine($"客户编号：{value.CustomerCode}");
                    message.AppendLine($"客户ID：{value.Id}");
                    message.AppendLine($"联系人：{value.ContactPerson}");
                    message.AppendLine($"联系电话：{value.ContactPhone}");

                    System.Windows.MessageBox.Show(message.ToString(), "选中的客户信息");
                }*/
            }
        }
        //定义总数据条数
        private int _totalRecordsSum;
        public int TotalRecordsSum
        {
            get => _totalRecordsSum;
            set
            {
                _totalRecordsSum = value;
                OnPropertyChanged(nameof(TotalRecordsSum));
            }
        }
        // 定义事项列表属性
        private ObservableCollection<CommunicationTypeModel> _commTypes = new ObservableCollection<CommunicationTypeModel>();
        public ObservableCollection<CommunicationTypeModel> CommTypes
        {
            get => _commTypes;
            set => SetProperty(ref _commTypes, value);
        }
        // 添加汇总数据属性  
        private ObservableCollection<CustomerSummaryModel> _customerSummary;
        public ObservableCollection<CustomerSummaryModel> CustomerSummary
        {
            get => _customerSummary;
            set
            {
                _customerSummary = value;
                OnPropertyChanged();
            }
        }
        // 定义选中的事项属性
        private CommunicationTypeModel _selectedCommType;
        public CommunicationTypeModel SelectedCommType
        {
            get => _selectedCommType;
            set => SetProperty(ref _selectedCommType, value);
        }
        //定义工作信息汇总查询命令
        private ICommand _queryCustomerSummary;
        public ICommand QueryCustomerSummary
        {
            get
            {
                return _queryCustomerSummary ?? (_queryCustomerSummary = new AsyncRelayCommand(LoadCustomerSummaryAsync));
            }
        }
        //初始化
        public CustomerSummaryViewModel() {
            //初始化数据库连接
            _db = DbContext.GetConnection();
            //初始化开始和结束时间
            StartDate = DateTime.Now;
            EndDate = DateTime.Now;
            // 初始化数据
            InitializeAsync();
        }
        //初始化方法
        private async void InitializeAsync()
        {
            try
            {
                await LoadCurtomers();
                await LoadAdmins();
                // 加载事项列表
                await LoadCommTypes();
            }
            catch (Exception ex)
            {
                Growl.Error($"初始化数据失败：{ex.Message}");
            }
        }
        //加载操作员列表
        private async Task LoadAdmins()
        {
            try
            {
                var admins = await _db.Queryable<AdminModel>()
                    .Where(a => a.Username.ToString() != "1001")
                    .ToListAsync();
                // 添加"全部"选项
                admins.Insert(0, new AdminModel
                {
                    Username = "",
                    Name = "全部"
                });
                Admins = new ObservableCollection<AdminModel>(admins);
                //设置默认操作员
                string currentAdminName = Application.Current.Properties["AdminName"]?.ToString();
                SelectedOperator = Admins.FirstOrDefault(a => a.Username == currentAdminName);
            }
            catch (Exception ex)
            {
                Growl.Error($"加载操作员列表失败：{ex.Message}");
            }
        }
        // 加载事项列表方法
        private async Task LoadCommTypes()
        {
            try
            {
                var types = await _db.Queryable<CommunicationTypeModel>().ToListAsync();

                // 添加"全部"选项
                types.Insert(0, new CommunicationTypeModel
                {
                    TypeCode = "",
                    TypeName = "全部"
                });

                CommTypes = new ObservableCollection<CommunicationTypeModel>(types);
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"加载事项列表失败：{ex.Message}");
            }
        }
        //加载客户列表
        private async Task LoadCurtomers()
        {
            try
            {
                var customers = await _db.Queryable<CustomerInfoModel>()
                    .ToListAsync();
                // 添加"全部"选项
                customers.Insert(0, new CustomerInfoModel
                {
                    Id = -1,
                    CompanyName = "全部"
                });
                Customers = new ObservableCollection<CustomerInfoModel>(customers);
            }
            catch (Exception ex)
            {
                Growl.Error($"加载客户列表失败：{ex.Message}");
            }
        }
        //加载客户汇总列表
        private async Task LoadCustomerSummaryAsync()
        {
            if (EndDate < StartDate)
            {
                System.Windows.MessageBox.Show($"开始日期不能大于结束日期！");
                return;
            }
            try
            {
                var startTime = StartDate.Date;
                var endTime = EndDate.Date.AddDays(1).AddSeconds(-1);
                // 直接查询汇总数据
                // 直接使用 GroupBy 和 Select 创建汇总数据
                var summary = await _db.Queryable<Infov1.Models.WorkForm.WorkRecordModel>()
                    .LeftJoin<CustomerInfoModel>((w, c) => w.CustomerId == c.Id)
                    //条件筛选
                    .Where(w => w.CreationTime >= startTime && w.CreationTime <= endTime)
                    .WhereIF(SelectedOperator != null && !string.IsNullOrEmpty(SelectedOperator.Username),
                             w => w.Operator == SelectedOperator.Username)
                    .WhereIF(SelectedCustomer != null && SelectedCustomer.Id > 0,
                             w => w.CustomerId == SelectedCustomer.Id)
                    .WhereIF(SelectedCommType != null && !string.IsNullOrEmpty(SelectedCommType.TypeCode),
                             w => w.CommTypeCode == SelectedCommType.TypeCode)
                    //按客户id和名称进行分组
                    .GroupBy((w, c) => new {
                        CustomerId = c.Id,
                        CompanyName = c.CompanyName
                    })
                    //按次数倒序排列
                    .OrderByDescending((w, c) => SqlFunc.AggregateCount(w.RecordId))
                    .Select((w, c) => new CustomerSummaryModel
                    {
                        CustomerId = c.Id,
                        CompanyName = c.CompanyName,
                        TotalRecords = SqlFunc.AggregateCount(w.RecordId)
                    })
                    .ToListAsync();
                // 计算总条数
                TotalRecordsSum = summary.Sum(item => item.TotalRecords);
                //更新汇总列表
                CustomerSummary = new ObservableCollection<CustomerSummaryModel>(summary);
                OnPropertyChanged(nameof(CustomerSummary));
             
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"加载列表失败信息失败！：{ex.Message}");
                // 打印详细错误信息以便调试
                System.Diagnostics.Debug.WriteLine($"错误详情：{ex}");
            }
        }
    }
}
